/*
 * @Description  : signalr
 * @Author       : zhao
 * @Date         : 2023-01-29 14:25:53
 * @LastEditors  : zhao
 * @LastEditTime : 2023-02-02 17:10:06
 */
import { defineStore } from 'pinia';

import { SignalrStates } from './interface';
import { CSGetBorrowingForm } from '/@/api/userInfo.js';
import { ElMessage } from 'element-plus';

import * as signalR from "@microsoft/signalr";
export const useSignalr = defineStore('signalr', {
    state: (): SignalrStates => ({
        signalr: null,
        isConnect: false,
        rec: null,// 断线重连后，延迟5秒重新创建WebSocket连接  rec用来存储延迟请求的代码,
        // wsUrl: 'http://175.188.189.182:10081/GeoArcShareInterface/ChatHub', // websocket 默认连接地址
        wsUrl: `${import.meta.env.VITE_API_URL as any}/ChatHub`, // websocket 默认连接地址
        unreadNum: 0,//未读数
    }),
    actions: {

        initWebSocket() {
            this.signalr = new signalR.HubConnectionBuilder().withAutomaticReconnect().withUrl(this.wsUrl, {}).build();

            this.signalr.on("broadcast", (id: any) => {

                this.unreadNum++

            });

            this.start()
        },


        async start() {
            try {
                await this.signalr.start();
            } catch (err) {
                console.log(err);
                setTimeout(this.start, 5000);
            }
        },


        async enter() {
            try {
                await this.signalr.invoke("Enter");
            } catch (err) {
                console.error(err);
            }
        },

        async quit() {
            try {
                await this.signalr.connection.invoke("Quit",);
            } catch (err) {
                console.error(err);
            }
        },
        eliminateUnreadNum() {

            this.unreadNum = 0
        }

    },
});